/**
 * Created by XianTao on 2016/11/7
 * <p/>
 * Copyright (c) 2015-2015
 * Apache License
 * Version 2.0, January 2004
 * http://www.apache.org/licenses/
 */
package org.lego.jpa.base.configuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.PropertyResolver;

import javax.sql.DataSource;
import java.sql.SQLException;

@Configuration
@Slf4j
public class DruidConfiguration {
    @Autowired
    private PropertyResolver propertyResolver;

    @Bean
    public ServletRegistrationBean druidServlet() {
        log.info("druid: Access database configuration via 'baseUrl/druid'");
        return new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
    }

    @Bean
    public DataSource druidDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(propertyResolver.getProperty("spring.datasource.driverClassName", ""));
        druidDataSource.setUrl(propertyResolver.getProperty("spring.datasource.url", ""));
        druidDataSource.setUsername(propertyResolver.getProperty("spring.datasource.username", ""));
        druidDataSource.setPassword(propertyResolver.getProperty("spring.datasource.password", ""));
        try {
            druidDataSource.setFilters("stat, wall");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return druidDataSource;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }
}
